package com.example.netty.chatSystem.message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
@Slf4j
public class MessageCodec1 extends ByteToMessageCodec<Message1> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext,
                          Message1 message, ByteBuf byteBuf) throws Exception {
        //简单粗略
        //1,4个字节的魔数
        byteBuf.writeBytes(new byte[]{1,2,3,4});
        //2,获取内容的字节数组
        //序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(message);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        //3,4个字节1的内容长度
        byteBuf.writeInt(bytes.length);
        //4,写入内容
        byteBuf.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf, List<Object> list) throws Exception {
        //简单粗略
        //1,读取4个字节的魔数
        int magic = byteBuf.readInt();
        //2,读取4个字节的长度
        int length = byteBuf.readInt();
        //3,读取内容
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes, 0, length);
        //反序列化
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Message1 message =  (Message1) objectInputStream.readObject();
        log.debug("{},{}",magic,length);
        log.debug("{}",message);
        list.add(message);
    }
}
